package com.szzg10.thinking.chapter18;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class GetChannel {

	public static void main(String[] args) throws IOException {
		//write
		File file = new File(BasicFileOutput.FILE_NAME_OUT);
		FileOutputStream fileOutputStream = new FileOutputStream(file);
		
		FileChannel channel = fileOutputStream.getChannel();
		channel.write(ByteBuffer.wrap(("Hello World!!!").getBytes()));
		channel.close();
		fileOutputStream.close();
		
		//random write
		RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
		channel = randomAccessFile.getChannel();
		
		channel.position(channel.size());
		channel.write(ByteBuffer.wrap(("\nAt the end!!!").getBytes()));
		channel.close();
		randomAccessFile.close();
		
		//read
		FileInputStream fileInputStream = new FileInputStream(file);
		channel = fileInputStream.getChannel();
		
		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
		channel.read(byteBuffer);
		byteBuffer.flip();
		while(byteBuffer.hasRemaining()) {
			System.out.print((char)(byteBuffer.get()));
		}
		
		channel.close();
		fileInputStream.close();
	}
}
